
import java.lang.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.TitledBorder;
import java.sql.*;
import java.util.ArrayList;

public class SelectionElement extends JFrame implements ActionListener {

  private JPanel pRech;
  private JPanel pRes;
  private JPanel pOutil;
  private JTable tRes;
  private JLabel lNom;
  private JTextField tNomTri;
  private JLabel lOrd;
  private JRadioButton rASC;
  private JRadioButton rDESC;
  private JLabel lCat;
  private JComboBox cbCat;
  private JButton bRech;
  private JButton bMod;
  private JButton bSup;
  private JButton bQuit;
  private JScrollPane scroll;
  private Container contenu;
  private ButtonGroup bg;

  public SelectionElement() {
    super("Recherche d'élément");
    this.setLayout(null);

    this.pRech = new JPanel(null, false);
    this.pRech.setBorder(new TitledBorder(null, "Recherche", TitledBorder.LEFT, TitledBorder.DEFAULT_POSITION));

    this.pRes = new JPanel(null, false);
    this.pRes.setBorder(new TitledBorder(null, "Resultat", TitledBorder.LEFT, TitledBorder.DEFAULT_POSITION));

    this.pOutil = new JPanel(null, false);
    this.pOutil.setBorder(new TitledBorder(null, "Outil", TitledBorder.LEFT, TitledBorder.DEFAULT_POSITION));

    this.lNom = new JLabel("Description de l'élément: ");
    this.lOrd = new JLabel("Par ordre: ");
    this.lCat = new JLabel("Categorie: ");

    this.tNomTri = new JTextField();

    this.loadTableauElem(true, false);
    //affichage dynamique des catégorie
    ArrayList<Categorie> categs = null;
    try {
      categs = Categorie.chargerCategories();
    } catch (SQLException errUser) {
      JOptionPane.showMessageDialog(this, "Erreur dans le chargement des catégories \n" + errUser, "Erreur BDD", JOptionPane.ERROR_MESSAGE);
    }
    String[] listeCategs = new String[categs.size() + 1];
    listeCategs[0] = "Toutes";
    int i = 1;
    for (Categorie c : categs) {
      listeCategs[i] = c.getNom();
      i++;
    }
    this.cbCat = new JComboBox(listeCategs);
    this.cbCat.setMaximumRowCount(5);

    this.bg = new ButtonGroup();
    this.rASC = new JRadioButton("Croissant", true);
    this.rDESC = new JRadioButton("Decroissant");
    this.bg.add(this.rASC);
    this.bg.add(this.rDESC);

    this.bRech = new JButton("Recherche");
    this.bRech.addActionListener(this);

    this.bMod = new JButton("Modifier");
    this.bMod.addActionListener(this);

    this.bSup = new JButton("Supprimer");
    this.bSup.addActionListener(this);

    this.bQuit = new JButton("Quitter");
    this.bQuit.addActionListener(this);

    this.contenu = this.getContentPane();
    this.contenu.setLayout(null);

    this.pRech.add(this.lNom);
    this.pRech.add(this.tNomTri);
    this.pRech.add(this.lOrd);
    this.pRech.add(this.rASC);
    this.pRech.add(this.rDESC);
    this.pRech.add(this.bRech);
    this.pRech.add(this.cbCat);
    this.pRech.add(this.lCat);
    //this.pRes.add(this.scroll);
    this.pOutil.add(this.bMod);
    this.pOutil.add(this.bQuit);
    this.pOutil.add(this.bSup);
    this.contenu.add(this.pRes);
    this.contenu.add(this.pRech);
    this.contenu.add(this.pOutil);

    this.pRech.setBounds(10, 10, 565, 175);
    this.pRes.setBounds(10, 200, 450, 300);
    this.pOutil.setBounds(475, 200, 150, 300);
    //this.scroll.setBounds(10,30,430,200);
    this.lNom.setBounds(15, 20, 150, 20);
    this.tNomTri.setBounds(180, 20, 100, 20);
    this.lOrd.setBounds(15, 90, 100, 20);
    this.rASC.setBounds(120, 90, 100, 20);
    this.rDESC.setBounds(220, 90, 100, 20);
    this.bRech.setBounds(90, 120, 105, 20);
    this.bMod.setBounds(25, 30, 100, 20);
    this.bSup.setBounds(25, 80, 100, 20);
    this.bQuit.setBounds(25, 130, 100, 20);
    this.cbCat.setBounds(180, 60, 100, 20);
    this.lCat.setBounds(15, 60, 100, 20);

    this.setBounds(50, 50, 650, 600);
    this.setVisible(true);
    this.setResizable(false);


  }

  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == this.bRech) {
      this.loadTableauElem(false, true);
    } else if (e.getSource() == this.bMod) {
      this.modifierElem();
    } else if (e.getSource() == this.bQuit) {
      this.dispose();
    } else if (e.getSource() == this.bSup) {
      this.supElem();
    }
  }

  public Item getSelectedItem(int selection) {
    return new Item(Integer.parseInt((String) this.tRes.getValueAt(selection, 0)), (String) this.tRes.getValueAt(selection, 1), new Categorie(Integer.parseInt((String) this.tRes.getValueAt(selection, 2)), (String) this.tRes.getValueAt(selection, 3)));
  }

  private void loadTableauElem(boolean callFromConstructor, boolean tri) {
    String[] colonnes = new String[]{"ID", "Description", "ID categorie", "Catégorie"};
    String ordre = new String("ASC");
    ArrayList<Item> items = null;
    try {
      if (tri) {
        if (this.rDESC.isSelected()) {
          ordre = "DESC";
        }
        items = Item.getItemByName(this.tNomTri.getText(), ordre);
      } else {
        items = Item.chargerItems();
      }
    } catch (SQLException e) {
      JOptionPane.showMessageDialog(this, "Erreur dans le chargement des items \n" + e, "Erreur BDD", JOptionPane.ERROR_MESSAGE);
    }

    if (tri) {
      String cat = (String) this.cbCat.getSelectedItem();
      ArrayList<Item> trash = new ArrayList<Item>();
      if (!cat.equals("Toutes")) {
        for (Item it : items) {
          if (!it.getCategorie().getNom().equals(cat)) {
            trash.add(it);
          }
        }

        for (Item it : trash) {
          items.remove(it);
        }
      }
    }

    Object[][] itemTab = new String[items.size()][3];
    int i = 0;
    for (Item it : items) {
      itemTab[i] = new String[]{String.valueOf(it.getId()), it.getNom(), String.valueOf(it.getCategorie().getId()), it.getCategorie().getNom()};
      i++;
    }

    // On met à jour le tableau en enlevant l'ancien et en le reconstruisant

    if (!callFromConstructor) {
      this.pRes.remove(this.scroll);
    }

    this.tRes = new JTable(itemTab, colonnes);
    this.scroll = new JScrollPane(this.tRes);
    this.scroll.createVerticalScrollBar();

    this.pRes.add(this.scroll);

    this.scroll.setBounds(10, 30, 430, 200);

  }

  private void modifierElem() {
    int selection = this.tRes.getSelectedRow();
    if (selection >= 0) {
      if (this.tRes.getSelectedRowCount() == 1) {
        GererItem gi = new GererItem(this.getSelectedItem(selection));
        this.loadTableauElem(false, false);
      } else {
        JOptionPane.showMessageDialog(this, "Vous ne pouvez sélectionner qu'un seul élément", "Modifier l'élément", JOptionPane.ERROR_MESSAGE);
      }
    } else {
      JOptionPane.showMessageDialog(this, "Vous devez sélectionner un élément", "Modifier l'élément", JOptionPane.ERROR_MESSAGE);
    }
  }

  private void supElem() {
    int selection = this.tRes.getSelectedRow();
    if (selection >= 0) {
      if (this.tRes.getSelectedRowCount() == 1) {
        int confirm = JOptionPane.showConfirmDialog(this, "Êtes-vous sûr de vouloir supprimer cet élément ?", "Supprimer l'élément", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
        if (confirm == JOptionPane.OK_OPTION) {
          try {
            getSelectedItem(selection).delete();
            JOptionPane.showMessageDialog(this, "L'élément a bien été supprimée.", "Supprimer l'élément", JOptionPane.INFORMATION_MESSAGE);
            this.loadTableauElem(false, false);
          } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "La suppression n'a pas pu aboutir.", "Supprimer l'élément", JOptionPane.ERROR_MESSAGE);
          }
        }
      } else {
        JOptionPane.showMessageDialog(this, "Vous ne pouvez sélectionner qu'un seul élément.", "Supprimer l'élément", JOptionPane.ERROR_MESSAGE);
      }
    } else {
      JOptionPane.showMessageDialog(this, "Vous devez sélectionner un élément.", "Supprimer l'élément", JOptionPane.ERROR_MESSAGE);
    }
  }
}
